package com.ljy.jymail.ware.service.impl;

import com.ljy.common.constant.WareConstant;
import com.ljy.jymail.ware.entity.PurchaseDetailEntity;
import com.ljy.jymail.ware.service.PurchaseDetailService;
import com.ljy.jymail.ware.service.WareSkuService;
import com.ljy.jymail.ware.vo.MergeVo;
import com.ljy.jymail.ware.vo.PurchaseDoneVo;
import com.ljy.jymail.ware.vo.PurchaseItemDoneVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ljy.common.utils.PageUtils;
import com.ljy.common.utils.Query;

import com.ljy.jymail.ware.dao.PurchaseDao;
import com.ljy.jymail.ware.entity.PurchaseEntity;
import com.ljy.jymail.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.constraints.NotNull;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {


    @Autowired
    PurchaseDetailService purchaseDetailService;

    @Autowired
    WareSkuService wareSkuService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageUnreceive(Map<String, Object> params) {
        QueryWrapper<PurchaseEntity> wrapper = new QueryWrapper<>();

        wrapper.eq("status",0).or().eq("status",1);
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);



    }


    /*
    * 合并采购单
    * */
    @Transactional
    @Override
    public void merge(MergeVo mergeVo) {
        Long purchaseId = mergeVo.getPurchaseId();
        if (purchaseId == null){
            PurchaseEntity purchaseEntity = new PurchaseEntity();

            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }

        //TODO 确认采购单状态是0或者1才可以合并

        List<Long> items = mergeVo.getItems();
        Long finalPurchasedId = purchaseId;
        List<PurchaseDetailEntity> collect = items.stream().map(i -> {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            purchaseDetailEntity.setId(i);
            purchaseDetailEntity.setPurchaseId(finalPurchasedId);
            purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
            return purchaseDetailEntity;
        }).collect(Collectors.toList());

        purchaseDetailService.updateBatchById(collect);

        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseId);
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
    }


    /*
    * 领取采购单
    *
    * */
    @Override
    public void received(List<Long> ids) {
        //1.确认当前采购单是新建还是已分配状态
        List<PurchaseEntity> collect = ids.stream().map(id -> {
            PurchaseEntity byId = this.getById(id);
            return byId;
        }).filter((item)->{
           if(item.getStatus()==WareConstant.PurchaseStatusEnum.CREATED.getCode()
           ||WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()==item.getStatus()){
               return true;
           }else {
               return false;
           }
        }).map(item->{
            item.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
            item.setUpdateTime(new Date());
            return item;
        }).collect(Collectors.toList());
        //2.改变采购单状态
        this.updateBatchById(collect);
        //3.改变采购项状态
        collect.forEach(item->{
            List<PurchaseDetailEntity> entityList =
                    purchaseDetailService.listDetailByPurchaseId(item.getId());
            List<PurchaseDetailEntity> details = entityList.stream().map(entity -> {
                PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
                detailEntity.setId(entity.getId());
                detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
                return detailEntity;
            }).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(details);
        });
    }


    /*完成采购订单*/
    @Transactional
    @Override
    public void done(PurchaseDoneVo doneVo) {

        //改变采购单状态
        Long id = doneVo.getId();


        //改变采购项状态
        Boolean flag = true;
        List<PurchaseItemDoneVo> items = doneVo.getItems();
        List<PurchaseDetailEntity> updates = new ArrayList<>();
        for (PurchaseItemDoneVo item:items){
            PurchaseDetailEntity entity = new PurchaseDetailEntity();
            if (item.getStatus()==WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()){
                flag=false;
                entity.setStatus(item.getStatus());
            }else {
                entity.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());


                PurchaseDetailEntity detailEntity = purchaseDetailService.getById(item.getItemId());
                wareSkuService.addStock(detailEntity.getSkuId(),detailEntity.getWareId(),detailEntity.getSkuNum());

            }

            entity.setId(item.getItemId());
            updates.add(entity);
        }

        purchaseDetailService.updateBatchById(updates);

        //将成功采购的进行入库
        PurchaseEntity entity = new PurchaseEntity();
        entity.setId(id);
        entity.setStatus(
                flag?WareConstant.PurchaseDetailStatusEnum.FINISH.getCode() :
                        WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode());
        entity.setUpdateTime(new Date());
        this.updateById(entity);


        //
    }

}